package com.estronger.shopmanage.fragment.orderQuery;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.estronger.pull_to_refresh_expandablelist.CommonFooterView.State;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshBase;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshBase.OnRefreshListener;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshListView;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.ui.order.activity.OrderDetailActivity;
import com.estronger.shopmanage.ui.order.activity.OrderQueryActivity;
import com.estronger.shopmanage.ui.order.adapter.QueryAdapter;
import com.estronger.shopmanage.ui.order.bean.OrderBean;
import com.estronger.shopmanage.ui.order.bean.returnMsgEntity;
import com.estronger.shopmanage.ui.order.until.Tools;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.CircularProgress;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import cn.jesse.nativelogger.NLogger;

public abstract class OrderBaseFragment extends Fragment implements
        OnRefreshListener<ListView> {

    protected PullToRefreshListView mListView;// 下拉刷新的ListView
    protected RequestParams params;
    protected LinearLayout root;// 根View
    protected CircularProgress bar;// 进度条
    protected TextView empty_view;// 没数据时展示
    protected QueryAdapter adapter;// 适配器
    // 存放测量条目数据
    protected ArrayList<OrderBean> data = new ArrayList<OrderBean>();
    private OrderQueryActivity activity;
    public int totalPage = 1;//总页数
    private int pagesize = 10;
    public static boolean isRestart = false;//当前Fragment或Activity是否是从被覆盖状态重新可见的情况？

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        activity = (OrderQueryActivity) getActivity();
        root = (LinearLayout) View.inflate(activity,
                R.layout.fragment_orderquery, null);
        mListView = (PullToRefreshListView) root
                .findViewById(R.id.success_listview);

        bar = (CircularProgress) root.findViewById(R.id.loding_view);
        empty_view = (TextView) root.findViewById(R.id.empty_view);
        mListView.setOnRefreshListener(this);
        mListView.setState(State.HIDE);
        adapter = new QueryAdapter(activity);
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OrderBean oBean = adapter.getItem(position - 1);
                Intent intent = new Intent(activity, OrderDetailActivity.class);
                intent.putExtra("LASTPOST", position - 1);
                intent.putExtra("Order", oBean);
                activity.startActivity(intent);
            }
        });
        loadData(true, gettype());
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (empty_view.getVisibility() == View.VISIBLE) {
            loadData(true, gettype());
        }
    }

    protected abstract boolean needConnect();

    protected abstract String gettype();

    public void loadData(final boolean isNeedDialog, final String type) {
        try {
            if (!NetUtils.isNetworkConnected(activity)) {
                mListView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mListView.onRefreshComplete();
                        Toast.show(activity, "当前无网络链接！", 2000);
                        if (data == null || data.size() > 0) {
                            adapter.resfNullData();
                            empty_view.setVisibility(View.VISIBLE);
                        }
                    }
                }, 1000);
                return;
            }
            final List<OrderBean> attList = new ArrayList<>();
            String url = MyApplication.getApplication().getSERVER_URL() + "/web/common/API/apphandler.ashx";
            RequestParams params = new RequestParams();
            params.addBodyParameter("sf_action", "getpreordlist");
            params.addBodyParameter("usercode", MyApplication.getUserCode());
            params.addBodyParameter("gettype", type);
            params.addBodyParameter("search", OrderQueryActivity.seaContext);
            params.addBodyParameter("pagesize", String.valueOf(pagesize));
            params.addBodyParameter("pageindex", String.valueOf(Tools.indexMap.get(type)));

            HttpUtils httpUtils = new HttpUtils();
            httpUtils.configTimeout(15 * 1000).configSoTimeout(15 * 1000).configRequestRetryCount(3);
            httpUtils.send(HttpRequest.HttpMethod.POST, url, params,
                    new RequestCallBack<String>() {
                        @Override
                        public void onStart() {
                            super.onStart();
                            if (isNeedDialog) {
                                if (null != bar) bar.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            try {
                                returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(responseInfo.result);
                                if (re != null) {
                                    if (re.getSuccess()) {
                                        JSONObject jj = new JSONObject(re.getDataJson());
                                        int totalNum = Tools.ToDefaultInt(jj.getString("total"));
                                        if (totalNum % pagesize == 0) {
                                            totalPage = totalNum / pagesize;
                                        } else {
                                            totalPage = (totalNum / pagesize) + 1;
                                        }
                                        JSONArray ra = new JSONArray(jj.getString("list"));
                                        if (ra != null && ra.length() != 0) {
                                            for (int i = 0; i < ra.length(); i++) {
                                                OrderBean ob = new OrderBean();
                                                JSONObject o = ra.getJSONObject(i);
                                                ob.setfItemId(Tools.ToString(o.getString("ordid")));
                                                ob.setfHouses(Tools.ToString(o.getString("buildName")));
                                                ob.setfCusName(Tools.ToString(o.getString("cstName")));
                                                ob.setfPhoneNumber(Tools.ToString(o.getString("cstMobile")));
                                                ob.setfOrdersTime(Tools.ToString(o.getString("ordRDate")));
                                                attList.add(ob);
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            afterResult(attList);
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            afterResult(attList);
                            try {
                                Toast.show(getActivity(), "网络或服务器异常", Toast.LENGTH_SHORT);
                            } catch (Exception ee) {
                            }
                        }
                    });
        } catch (Exception e) {
            NLogger.e("加载统计数据异常:" + e.getMessage());
        }
    }

    private void afterResult(List<OrderBean> attList) {
        if (null != bar) bar.setVisibility(View.GONE);
        if (null != mListView) {
            mListView.setState(State.HIDE);
            mListView.onRefreshComplete();
        }
        if (Tools.indexMap.get(gettype()) == 1) {
            data.clear();
            if (attList.size() >= pagesize) {
                mListView.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }
        data.addAll(attList);
        if (data.size() > 0) {
            empty_view.setVisibility(View.GONE);
            adapter.appendData(data, true);
            mListView.setSelection((Tools.indexMap.get(gettype()) - 1) * pagesize);
        } else {
            if (OrderQueryActivity.isSearch) {
                Toast.show(activity, "未找到符合条件的预订单！", Toast.LENGTH_SHORT);
            }
            OrderQueryActivity.isSearch = false;
            adapter.resfNullData();
            empty_view.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 下拉刷新时调用
     */
    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        isRestart = false;
        if (mListView.isHeaderShown()) {
            Tools.indexMap.put(gettype(), 1);
            if (activity != null) {
                activity.getTitleNum();
            } else {
                activity = (OrderQueryActivity) getActivity();
            }
            loadData(false, gettype());
        } else if (mListView.isFooterShown()) {
            if (Tools.indexMap.get(gettype()) >= totalPage) {
                mListView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mListView.onRefreshComplete();
                        Toast.show(getActivity(), "没有更多了！", Toast.LENGTH_SHORT);
                    }
                }, 500);
            } else {
                Tools.indexMap.put(gettype(), Tools.indexMap.get(gettype()) + 1);
                loadData(false, gettype());
            }
        }
    }
}
